package com.sgb.knowledgeshare.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentSharehomeUserBinding;
import com.sgb.knowledgeshare.entity.ShareUserInfoEntity;
import com.sgb.knowledgeshare.entity.UserBean;
import com.sgb.knowledgeshare.utils.PageChangeEvent;
import com.sgb.knowledgeshare.utils.RxBus;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.sgb.knowledgeshare.view.activity.ShareUserAttentionActivity;
import com.sgb.knowledgeshare.view.activity.ShareUserFansActivity;
import com.sgb.knowledgeshare.view.adapter.ShareUserListAdapter;
import com.sgb.knowledgeshare.viewmodel.ShareHomeUserModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.VideoListEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import rx.functions.Action1;

public class ShareHomeUserFragment extends AppLazyFragment {

    public static final int USER_PRODUCTION_TYPE = 0;//作品
    public static final int USER_LIKE_TYPE = 1;//喜欢
    ShareHomeUserModel viewmode;
    private FragmentSharehomeUserBinding binding;
    private String userid = "";
    private int curPos = 0;
    private ShareUserListAdapter shareuserlistadapter;
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private int pages;
    private boolean isLoadMore = false;
    private int page;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sharehome_user, container, false);
        viewmode = new ViewModelProvider(this).get(ShareHomeUserModel.class);
        viewmode.setActivity(ShareHomeUserFragment.this);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        page = 1;
        initData();
    }

    @Override
    public void onVisible() {
        super.onVisible();
        page = 1;
        initData();
    }

    private void initData() {
        // 获取用户信息数据
        if (!TextUtils.isEmpty(userid)) {
            DialogHelper.showProgressDialog(getActivity(), null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
            viewmode.getUserHomePage(userid);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().toObservable(UserBean.class).subscribe((Action1<UserBean>) UserBean -> {
            userid = UserBean.getUserid();
        });

    }

    @Override
    protected void initView() {
        binding.llShareUserLike.setOnClickListener(this);//获赞
        binding.llShareUserAttention.setOnClickListener(this);//关注
        binding.llShareUserFans.setOnClickListener(this);//粉丝
        binding.backView.setOnClickListener(this);
        //        关注的点击事件
        binding.shareUserState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                        //请求接口数据、成功后再获取数据
                        if (!TextUtils.isEmpty(userid)) {
                            //请求接口数据、成功后再获取数据
                            viewmode.getFens(userid);
                        }
                    } else {
                        MToast.showToast(getContext(), "请实名认证完成后再进行点赞！");
                    }
                } else {
                    MToast.showToast(getContext(), "请先登录账户！");
                }
            }
        });
        binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                //verticalOffset始终为0以下的负数
                float percent = (Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange());
                binding.toolbar.setBackgroundColor(changeAlpha(Color.WHITE, percent));
            }
        });
        if (shareuserlistadapter == null) {
            shareuserlistadapter = new ShareUserListAdapter(getActivity(), null);
        }
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(shareuserlistadapter);
        GridItemDecoration divider = new GridItemDecoration.Builder(getContext())
                .setHorizontal(R.dimen.dp10)
                .setVertical(R.dimen.dp10)
                .setColorResource(R.color.white)
                .build();
        binding.lrecyclerview.addItemDecoration(divider);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        binding.lrecyclerview.setLayoutManager(layoutManager);
        binding.lrecyclerview.setAdapter(mLRecyclerViewAdapter);
        binding.lrecyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                shareuserlistadapter.clearDatas();
                mLRecyclerViewAdapter.notifyDataSetChanged();
                listData();
            }
        });
        binding.lrecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreData();
            }
        });
//    条目的点击事件
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), PlayListActivity.class);
                intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) shareuserlistadapter.getDatas());
                intent.putExtra(PlayListActivity.PSO, position);
                intent.putExtra(PlayListActivity.VIDEOTYPE, "fx_mine");
                intent.putExtra(PlayListActivity.PAGE, page);
                intent.putExtra(PlayListActivity.USERNO, userid + "");
                intent.putExtra(PlayListActivity.VIDEOTITLE, curPos + "");
                getActivity().startActivity(intent);
            }
        });
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                curPos = tab.getPosition();
                DialogHelper.showProgressDialog(getActivity(), null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
                listData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    //加载更多的处理方法
    private void loadMoreData() {
        isLoadMore = true;
        page++;
        if (page <= pages) {
            viewmode.getVideoListData(page, userid, curPos + "");
        } else {
            binding.lrecyclerview.setNoMore(true);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();//点赞
        if (id == R.id.ll_share_user_like) {
        } else if (id == R.id.ll_share_user_attention) {//关注
            ShareUserAttentionActivity.start(getContext(), userid);
        } else if (id == R.id.ll_share_user_fans) {//粉丝
            ShareUserFansActivity.start(getContext(), userid);
        } else if (id == R.id.back_view) {
            RxBus.getDefault().post(new PageChangeEvent(0));
        }
    }

    //请求数据
    private void listData() {
        isLoadMore = false;
        page = 1;
        viewmode.getVideoListData(page, userid, curPos + "");
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    //用户信息数据
    public void setUserData(ShareUserInfoEntity data) {

        if (data != null) {
//        头像
            if (!TextUtils.isEmpty(data.getPhoto())) {
                Glide.with(getContext()).load(data.getPhoto() + "")
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.share_def_photo))
                        .into(binding.shareUserLogo);
            } else {
                int resourceId = R.mipmap.share_def_photo;
                Glide.with(this)
                        .load(resourceId)
                        .into(binding.shareUserLogo);
            }
//        是否关注状态   0未关注、1已关注、2互相关注
//        share_user_state
            int isUserHomePage = data.getIsUserHomePage();
            if (isUserHomePage == 1) {//是否时自己的主页
                binding.shareUserState.setVisibility(View.GONE);
            } else {
                binding.shareUserState.setVisibility(View.VISIBLE);
            }
            switch (data.getIsFollow()) {
                case 0:
                    binding.shareUserState.setText("关注");
                    binding.shareUserState.setBackgroundColor(getResources().getColor(R.color.color_5792FD));
                    break;
                case 1:
                    binding.shareUserState.setText("取消关注");
                    binding.shareUserState.setBackgroundColor(getResources().getColor(R.color.color_C0C4CC));
                    break;
                case 2:
                    binding.shareUserState.setText("互相关注");
                    binding.shareUserState.setBackgroundColor(getResources().getColor(R.color.color_FFC000));
                    break;
            }

//        用户名称
            if (!TextUtils.isEmpty(data.getName())) {
                binding.shareUserName.setText(data.getName());
            } else {
                binding.shareUserName.setText("");
            }
            //公司名称
            if (!TextUtils.isEmpty(data.getCompanyName())) {
                binding.shareUserCompany.setText(data.getCompanyName());
            } else {
                binding.shareUserCompany.setText("");
            }
            //获赞数量
            binding.shareUserLike.setText(data.getLaudCount() + "");
            //关注数量
            binding.shareUserAttention.setText(data.getFollow() + "");
            //粉丝数量
            binding.shareUserFans.setText(data.getFens() + "");
            binding.tablayout.removeAllTabs();
            binding.tablayout.addTab(binding.tablayout.newTab().setText("作品  " + data.getCreateCount()));
            binding.tablayout.addTab(binding.tablayout.newTab().setText("喜欢  " + data.getLikeCount()));
            listData();
        } else {
            if (shareuserlistadapter != null && shareuserlistadapter.getDatas().size() > 0) {
                shareuserlistadapter.getDatas().clear();
                shareuserlistadapter.notifyDataSetChanged();
            }
        }
    }

    public void UpdataUserIfno() {
        initData();
    }

    //列表数据
    public void setVideoListData(VideoListEntity data) {
        DialogHelper.dismissProgressDialog();
        List<VideoBean> records = data.getRecords();
        pages = data.getPages();
        if (records == null) {
            shareuserlistadapter.setDatas(new ArrayList<>());
            return;
        }
        binding.lrecyclerview.refreshComplete(records.size());
        if (isLoadMore) {
            if (records.size() > 0) {
                shareuserlistadapter.addDatas(records);
            } else {
                MToast.showToast(getContext(), "没有视频啦!");
            }
        } else {
            if (records.size() > 0) {
                binding.lrecyclerview.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                shareuserlistadapter.setDatas(records);
            } else {
                binding.lrecyclerview.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
                shareuserlistadapter.setDatas(null);
            }
        }
    }

}
